//
//  AppDelegate.m
//  biz
//
//  Created by 小龙 on 2017/3/16.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import "BIZTabBarController.h"
#import "UMessage.h"
#import <UserNotifications/UserNotifications.h>
#import "BIZConsultDetailTableViewController.h"
#import "BIZRapidConsultResultVC.h"
#import "BIZOfflineConsultQuestionDetailVC.h"
#import "BIZOfficalVIPConsultDetailVC.h"

//// IM(支持实时语音)
//#import <HyphenateLite/HyphenateLite.h>
// Model
#import "BIZRemoteNotificationModel.h"
#import "BIZConsultQModel.h"
#import "BIZQuestionModel.h"
#import "BIZContractDetailVC.h"

#import <Bugly/Bugly.h>
#import "ReleaseConfirm.h"

#define BUGLY_APP_ID @"9ef1a0e9a1"

@interface AppDelegate ()<UNUserNotificationCenterDelegate, BuglyDelegate>
/** tabBarController */
@property (nonatomic, strong) BIZTabBarController *tabBarController;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 版本升级 请将我放到第一行
//    [[ReleaseConfirm DefultInstance] confirm];
    
    [self setupBugly];
    
    [self monitorNetWorkStatus];
    
    [self setupRootView];
    
    [self refreshSDWebImageCookie];
    
    [self configUmengPushWithOptions:launchOptions];
    
//    [self configIMhuanxin];
    
    [self configKeyBoard];

    [self configPrivateAudioAndVideo];
    
    return YES;
}
    
- (void)setupBugly
{
        // Get the default config
        BuglyConfig * config = [[BuglyConfig alloc] init];
        
        // Open the debug mode to print the sdk log message.
        // Default value is NO, please DISABLE it in your RELEASE version.
#if DEBUG
        config.debugMode = YES;
#endif
        
        // Open the customized log record and report, BuglyLogLevelWarn will report Warn, Error log message.
        // Default value is BuglyLogLevelSilent that means DISABLE it.
        // You could change the value according to you need.
        //    config.reportLogLevel = BuglyLogLevelWarn;
        
        // Open the STUCK scene data in MAIN thread record and report.
        // Default value is NO
        config.blockMonitorEnable = YES;
        
        // Set the STUCK THRESHOLD time, when STUCK time > THRESHOLD it will record an event and report data when the app launched next time.
        // Default value is 3.5 second.
        //    config.blockMonitorTimeout = 1.5;
        
        // Set the app channel to deployment
        config.channel = @"Bugly";
        
        config.delegate = self;
        
        config.consolelogEnable = NO;
        config.viewControllerTrackingEnable = NO;
        
        // NOTE:Required
        // Start the Bugly sdk with APP_ID and your config
        [Bugly startWithAppId:BUGLY_APP_ID
#if DEBUG
            developmentDevice:YES
#endif
                       config:config];
        
        // Set the customizd tag thats config in your APP registerd on the  bugly.qq.com
        // [Bugly setTag:1799];
        
        [Bugly setUserIdentifier:[NSString stringWithFormat:@"User: %@", [UIDevice currentDevice].name]];
        
        [Bugly setUserValue:[NSProcessInfo processInfo].processName forKey:@"Process"];
        
    }
    
#pragma mark - BuglyDelegate
- (NSString *)attachmentForException:(NSException *)exception {
    DeLog(@"(%@:%d) %s %@",[[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, __PRETTY_FUNCTION__,exception);
    
    return @"This is an attachment";
}


- (void)setupRootView
{
    if (![BIZUserModel shareUser].login) {
        self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
        self.window.backgroundColor = [UIColor whiteColor];
        BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
        vc.isNotLogin = YES;
        self.window.rootViewController = vc;
        [self.window makeKeyAndVisible];
    } else {
        [self configRootViewController];
    }
}

- (void)configRootViewController
{
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
}


- (void)dealloc
{
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)configUmengPushWithOptions:(NSDictionary *)launchOptions
{
    // 消息推送初始化(适配 https)
    [UMessage startWithAppkey:kUmengPushAppKey launchOptions:launchOptions httpsEnable:YES];
    
    // 注册通知
    [UMessage registerForRemoteNotifications];
    
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
    DeLog(@"launchOptions--%@",launchOptions);
}

//- (void)configIMhuanxin {
//    //AppKey:注册的AppKey，详细见下面注释。
//    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
//    EMOptions *options = [EMOptions optionsWithAppkey:@"1151161223115859#imtest"];
//    options.apnsCertName = @"istore_dev";
//    [[EMClient sharedClient] initializeSDKWithOptions:options];
//
//}


#pragma mark -- 通知相关方法
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
    DeLog(@"UmengDeviceToken-%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""]);
    
    
//    // 设置推送 alias
//    BIZUserDetailModel *userDetailM = [BIZUserModel shareUser].detailModel;
//    DeLog(@"set alias--%@",userDetailM.uuid);
//    if (userDetailM.uuid) {
//    
//        [UMessage setAlias:userDetailM.uuid type:@"alias" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
//            
//            if (error) {
//                DeLog(@"set alias err %@", error);
//            }else {
//                DeLog(@"set alias successfully--%@" ,responseObject);
//            }
//            
//        }];
//    }
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    if ([[[UIDevice currentDevice] model] rangeOfString:@"Simulator"].location != NSNotFound) {
        
        DeLog(@"apns is NOT supported on simulator, run your Application on a REAL device to get device token");
        
    }else{
        
        DeLog(@"DeviceToken 获取失败--%@",error);
    }
}

#pragma mark - 远程通知 >7.0
// 此方法是 用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
    DeLog(@"applicationState %ld", application.applicationState);
    DeLog(@"fetch 收到一条消息 : %@", userInfo);
    
    [self showCustomRemoteNotificationAlertWithUserInfo:userInfo];
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    DeLog(@"fetch 收到一条消息 : %@", userInfo);
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        [self showCustomRemoteNotificationAlertWithUserInfo:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        [self showCustomRemoteNotificationAlertWithUserInfo:userInfo];
    }else{
        //应用处于后台时的本地推送接受
    }
    
}

// 自定义推送弹窗
- (void)showCustomRemoteNotificationAlertWithUserInfo:(NSDictionary *)userInfo {
    // 关闭友盟弹窗
    [UMessage setAutoAlert:NO];
    //必须加这句代码
    [UMessage didReceiveRemoteNotification:userInfo];
    
    DeLog(@"推送的消息:%@",userInfo);
    
   
    
    BIZRemoteNotificationModel *notiM = [BIZRemoteNotificationModel yy_modelWithDictionary:userInfo];
    
    
    BIZNavigationController *nav = (BIZNavigationController *)(self.tabBarController.selectedViewController);
    NSArray *viewControllerArr = nav.viewControllers;
    
    [self getTabBarRedBadgeData];
    // UIAlertViewController(弹框视图)
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"通知" message:userInfo[@"aps"][@"alert"] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confim = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        DeLog(@"点击了确定");
        switch (notiM.type.intValue) {
            case 1:{
                // MARK:TO DO  跳转到一对一
                for (UIViewController *viewController in viewControllerArr) {
                    if ([viewController isKindOfClass:[BIZConsultDetailTableViewController class]]) {
                        [nav popViewControllerAnimated:YES];
                        break;
                    }
                }
                
                BIZConsultDetailTableViewController *vc = [[BIZConsultDetailTableViewController alloc] init];\
                BIZConsultQModel *model = [[BIZConsultQModel alloc]init];
                model.uuid = notiM.uuid;
                model.name = notiM.userName;
                model.content = notiM.content;
                model.imgs = notiM.images;
                model.updateTime = notiM.date;
                
                vc.qModel = model;
                vc.needLoadAnswer = YES;
                
                [self.tabBarController.selectedViewController pushViewController:vc animated:YES];

            }
                break;
            case 2:{
                // MARK:TO DO  跳转到快速咨询
                
                for (UIViewController *viewController in viewControllerArr) {
                    if ([viewController isKindOfClass:[BIZRapidConsultResultVC class]]) {
                        [nav popViewControllerAnimated:YES];
                        break;
                    }
                }
                
                BIZRapidConsultResultVC *vc = [[BIZRapidConsultResultVC alloc]init];
                vc.alertTitleStr = nil;
                BIZQuestionModel *model = [[BIZQuestionModel alloc]init];
                model.uuid = notiM.uuid;
                model.name = notiM.userName;
                model.content = notiM.content;
                model.imgs = notiM.images;
                model.updateTime = notiM.date;
                vc.questionModel = model;
                
                
                vc.adoptBtnClickBlock = ^(){
                    [[NSNotificationCenter defaultCenter] postNotificationName:kReloadRepaidListNotification object:nil];
                    
                };
                [self.tabBarController.selectedViewController pushViewController:vc animated:YES];
            }
                
                break;
            case 3:{
                // MARK:TO DO  跳转到线下咨询
                
                for (UIViewController *viewController in viewControllerArr) {
                    if ([viewController isKindOfClass:[BIZOfflineConsultQuestionDetailVC class]]) {
                        [nav popViewControllerAnimated:YES];
                        break;
                    }
                }
                
                BIZOfflineConsultQuestionDetailVC *vc = [[BIZOfflineConsultQuestionDetailVC alloc] initWithQuestionUuid:notiM.uuid];
                
                [self.tabBarController.selectedViewController pushViewController:vc animated:YES];

            }
                
                break;
            case 4:{
                // MARK:TO DO  跳转到合同审核
                for (UIViewController *viewController in viewControllerArr) {
                    if ([viewController isKindOfClass:[BIZContractDetailVC class]]) {
                        [nav popViewControllerAnimated:YES];
                        break;
                    }
                }
                
                BIZContractDetailVC *vc = [[BIZContractDetailVC alloc] init];
                vc.uuid = notiM.uuid;
                vc.isPush = YES;
                [nav pushViewController:vc animated:YES];
                
            }
            case 5:{
                // MARK:TO DO  跳转到官方咨询
                for (UIViewController *viewController in viewControllerArr) {
                    if ([viewController isKindOfClass:[BIZOfficalVIPConsultDetailVC class]]) {
                        [nav popViewControllerAnimated:YES];
                        break;
                    }
                }
                
                BIZOfficalVIPConsultDetailVC *vc = [[BIZOfficalVIPConsultDetailVC alloc] initWithUUID:notiM.uuid];
                [nav pushViewController:vc animated:YES];
                
            }
                break;
            default:
                break;
        }
        
    }];
    [alertView addAction:confim];
    
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        DeLog(@"点击了取消");
    }];
    [alertView addAction:cancel];
    
    [self.window.rootViewController presentViewController:alertView animated:YES completion:nil];

}

- (void)configKeyBoard
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = NO;
}

- (void)configPrivateAudioAndVideo {
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {//相机权限
        if (granted) {
            NSLog(@"Authorized");
        }else{
            NSLog(@"Denied or Restricted");
        }
    }];
    
//    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {//麦克风权限
//        if (granted) {
//            NSLog(@"Authorized");
//        }else{
//            NSLog(@"Denied or Restricted");
//        }
//    }];
}

- (void)refreshSDWebImageCookie
{
    [SDWebImageTool refreshCookieId:[BIZUserModel shareUser].cookieID];
}

- (void)monitorNetWorkStatus
{
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                [MBProgressHUD showInfoMessage:@"正在使用wifi" timer:1.5];
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                DeLog(@"手机网络");
                [MBProgressHUD showInfoMessage:@"正在使用手机网络" timer:1.5];
                break;
            }
            case AFNetworkReachabilityStatusNotReachable:
            {
                DeLog(@"没有网络");
                [MBProgressHUD showInfoMessage:@"没有网络，请检查网络" timer:2];
                break;
            }
            case AFNetworkReachabilityStatusUnknown:
            {
                DeLog(@"未知网络");
                [MBProgressHUD showInfoMessage:@"未知网络" timer:1.5];
                break;
            }
            default:
                break;
        }
    }];
    
    // 开始监控
    [mgr startMonitoring];
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//    [[EMClient sharedClient] applicationDidEnterBackground:application];

}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
//    [[EMClient sharedClient] applicationWillEnterForeground:application];

}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


-(BIZTabBarController *)tabBarController
{
    if (!_tabBarController) {
        _tabBarController = [[BIZTabBarController alloc]init];
    }
    
    return _tabBarController;
}



- (void)getTabBarRedBadgeData
{
    if (![BIZUserModel shareUser].login) {
        return;
    }
    
    [RequestTool POST:kTabBarRedBadgeUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"kTabBarRedStatusURL---responseObject %@", responseObject);
        
        if ([responseObject[@"code"] integerValue] == 1) {
            
            if (([responseObject[@"data"][@"oneRed"] integerValue])
                ||([responseObject[@"data"][@"contractRed"] integerValue])
                ||([responseObject[@"data"][@"lineDownRed"] integerValue])) {
                [self.tabBarController.tabBar.items[0] showBadge];
            } else {
                [self.tabBarController.tabBar.items[0] hidenBadge];
            }
            
//            if (([responseObject[@"data"][@"rapidRed"]  integerValue])) {
//                [self.tabBarController.tabBar.items[1] showBadge];
//            } else {
//                [self.tabBarController.tabBar.items[1] hidenBadge];
//            }
            
        }
        else {
            [MBProgressHUD showInfoMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
        if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
            [MBProgressHUD showErrorMessage:@"网络不给力"];
        }
        else {
            [MBProgressHUD showErrorMessage:@"服务器繁忙"];
        }
    }];
}

@end
